const startButton = document.getElementById('startButton');

startButton.addEventListener('click', () => {
    navigator.mediaDevices.getDisplayMedia({video: true})
    .then(handleSuccess, handleError);
});

function handleSuccess(stream) {
    startButton.disabled = true;
    const video = document.querySelector('video');
    video.srcObject = stream;

    // 检测用户已停止共享屏幕
    // 通过浏览器UI共享屏幕。
    stream.getVideoTracks()[0].addEventListener('ended', () => {
          errorMsg('用户已结束共享屏幕');
          startButton.disabled = false;
    });
}

function handleError(error) {
    errorMsg(`getDisplayMedia error: ${error.name}`, error);
}

function errorMsg(msg, error) {
    const errorElement = document.querySelector('#errorMsg');
    errorElement.innerHTML += `<p>${msg}</p>`;
    if (typeof error !== 'undefined') {
          console.error(error);
    }
}
